import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool{
    // 任务队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    // 添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        // 此处相当于拒绝策略了,就是第五种策略,阻塞等待了
        queue.put(runnable);
    }

    public MyThreadPool(int n){
        // 创建出n个线程负责上述任队列中的任务
        for(int i = 0;i < n;i++) {
            Thread t = new Thread(() -> {
                try {
                    Runnable runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }
}
public class Demo28 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(4);
        for(int i = 0;i < 1000;i++){
            int id = i;
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    // 在匿名内部类中涉及了变量捕获问题,id就是
                    System.out.println("执行任务 + " + id);
                }
            });
        }
    }
}
